//
//  ILDailySelectDetailViewController.m
//  ILife
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILDailySelectDetailViewController.h"
#import <UIImageView+WebCache.h>
#import "ILDailySelectModel.h"
#import <AFNetworking.h>
#import <MediaPlayer/MediaPlayer.h>
#import "ILDetailView.h"
#import "FMDatabase.h"

@interface ILDailySelectDetailViewController ()
@property (nonatomic,strong) MPMoviePlayerViewController *moviePlayerVC;//视频播放控制器
@property(nonatomic,strong)ILDetailView *mainView;

@property(nonatomic,strong)UIAlertView *alert;

//收藏

@property(nonatomic,strong)FMDatabase *dataBase;
@property(nonatomic,strong)UIButton *rightButton;

@end

@implementation ILDailySelectDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sqliteHandle:) name:@"A" object:@"A"];
    //数据源
    ILDailySelectModel *model = self.dataArr[self.index];
    //导航栏 右侧按钮
    _rightButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _rightButton.frame = CGRectMake(0, 0, 32, 32);
    [_rightButton setImage:[UIImage imageNamed:@"collect"] forState:(UIControlStateNormal)];
#pragma 判断是否已经收藏
    [self selectForTable:model];
    if ([model.isCollect isEqualToString:@"yes"]) {
        [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];
    }
    
    [_rightButton addTarget:self action:@selector(changeTheme:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightButton];
    self.mainView = [[ILDetailView alloc]initWithFrame:self.view.bounds];
    [self.mainView configureWithData:model];
   
    [self.view addSubview:_mainView];
#pragma  添加轻扫手势   轻扫手势，支持四个方向的轻扫，但是不同的方向要分别定义轻扫手势
    UISwipeGestureRecognizer *rightSwipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(switchInterface:)];
    rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
     UISwipeGestureRecognizer *leftSwipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(switchInterface:)];
    leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.mainView.backgroudImg addGestureRecognizer:rightSwipeGesture];
    [self.mainView.backgroudImg addGestureRecognizer:leftSwipeGesture];
#pragma  添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideo:)];
    [self.mainView.coverImg addGestureRecognizer:tapGesture];
    
    
    NSLog(@"aaaaaa");
    
}

//-(void)sqliteHandle:(NSNotification*)noti
//{
//    ILDailySelectModel *model = noti.userInfo[@"title"];
//    [self selectForTable:model];
//    
//}

//--------------手势实现--------------------------------
-(void)switchInterface:(UISwipeGestureRecognizer *)swip
{
    if (self.index<self.dataArr.count-1 && swip.direction == UISwipeGestureRecognizerDirectionLeft )
    {
        ILDailySelectModel *model = self.dataArr[++self.index];
        [self.mainView configureWithData:model];
        [self selectForTable:model];
        if ([model.isCollect isEqualToString:@"yes"])
        {
            [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];
        }
    }if (self.index> 0 &&swip.direction == UISwipeGestureRecognizerDirectionRight)
    {
        
        ILDailySelectModel *model = self.dataArr[--self.index];
        [self.mainView configureWithData:model];
        [self selectForTable:model];
        if ([model.isCollect isEqualToString:@"yes"])
        {
            [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];
        }
    }
}



//--------------------点击按钮  方法实现
-(void)changeTheme:(UIButton*)button
{
    ILDailySelectModel *model = [self.dataArr objectAtIndex:_index];
    if ([model.isCollect isEqualToString:@"no"])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否收藏?" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action)
        {
            [button setImage:[UIImage imageNamed:@"collected"]forState:(UIControlStateNormal)];
            ILDailySelectModel *model = [self.dataArr objectAtIndex:_index];
            model.isCollect = @"yes";
                  [self createDataBase:model];
        }];
        [alert addAction:cancelAction];
        [alert addAction:archiveAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
  _alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏了，换一个吧。" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(performDismiss) userInfo:nil repeats:NO];
        [_alert show];

    }
}

-(void)performDismiss
{
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
}



-(void)createDataBase:(ILDailySelectModel*)model
{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"ILive_Video.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"收藏====%@",filePath);
    if ([_dataBase open])
    {
    NSLog(@"数据库打开成功");
    [_dataBase executeUpdate:@"CREATE TABLE Video (coverBlurred text, coverForDetail text,  title text, duration integer, category text,des text, isCollect text)"];
    } else
    {
        NSLog(@"数据库打开失败");
    }
    [_dataBase executeUpdate:@"INSERT INTO Video (coverBlurred, coverForDetail, title, duration, category,des,isCollect) VALUES (?,?,?,?,?,?,?)",model.coverBlurred,model.coverForDetail,model.title,[NSNumber numberWithDouble:model.duration],model.category,model.des,model.isCollect];
}

-(void)selectForTable:(ILDailySelectModel*)model
{

        NSLog(@"=----------------------%@",model.title);
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"ILive_Video.db"];
        _dataBase = [FMDatabase databaseWithPath:filePath];
        if ([_dataBase open]) {
            NSLog(@"数据库打开成功");
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
            FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM Video"];
            while ([resultSet next])
            {
                NSString *str = [resultSet stringForColumn:@"title"];
                NSLog(@"---------%@",str);
                [arr addObject:str];
            }
            for (NSString *str in arr)
            {
                if ([model.title isEqualToString:str])
                {
                    model.isCollect = @"yes";
                    [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];
                }else
                {
                    [_rightButton setImage:[UIImage imageNamed:@"collect"] forState:(UIControlStateNormal)];
                }
            }
            [resultSet close];
        } else
        {
            NSLog(@"数据库打开失败");
            [_rightButton setImage:[UIImage imageNamed:@"collect"] forState:(UIControlStateNormal)];
        }
   
}

-(void)playVideo:(UITapGestureRecognizer *)tap
{
    NSLog(@"--------点我播放");
    ILDailySelectModel *model = self.dataArr[self.index];
    //播放
    self.moviePlayerVC = nil;
   [self moviePlayerWithURLstr:model.playUrl];
    [self presentMoviePlayerViewControllerAnimated:self.moviePlayerVC];
    
}


//**********************************视频播放******************************

-(void)dealloc{
    //移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  创建媒体播放控制器
 *
 *  @return 媒体播放控制器
 */
-(MPMoviePlayerViewController *)moviePlayerWithURLstr:(NSString *)urlString{
    if (!_moviePlayerVC) {
        NSString *urlStr= urlString;
        urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url=[NSURL URLWithString:urlStr];
        _moviePlayerVC=[[MPMoviePlayerViewController alloc]initWithContentURL:url];

#pragma 设置播放视频横屏
        _moviePlayerVC.view.frame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
        _moviePlayerVC.view.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
        [_moviePlayerVC.view setTransform:transform];

        //添加通知
        [self addNotification];
        
    }
    return _moviePlayerVC;
}


#pragma mark - 控制器通知
/**
 *  添加通知监控媒体播放控制器状态
 */
-(void)addNotification{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayerVC];
    
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayerVC];
    
}

/**
 *  播放状态改变，注意播放完成时的状态是暂停
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification{
    switch (self.moviePlayerVC.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放...");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        default:
            NSLog(@"播放状态:%ld",(long)self.moviePlayerVC.moviePlayer.playbackState);
            break;
    }
}

/**
 *  播放完成
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification{
    NSLog(@"播放完成.%ld",(long)self.moviePlayerVC.moviePlayer.playbackState);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
